package com.zsc.edu.testasyncmsg;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    final static String TAG = "---MainActivity---";
    Button btn_request;
    EditText edit_text_index;
    EditText edit_text_number;
    ImageView image_view;

    // 存储图片url
    List<String> image_url_list;

    Handler handler;

    final static int MSG_REQUEST_JSON = 1;
    final static int MSG_REQUEST_IMAGE = 2;

    final static int SLEEP_MM = 3000;
    final static String URL_PRE = "https://cn.bing.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_request = findViewById(R.id.btn_request);
        image_view = findViewById(R.id.image_view);
        edit_text_index = findViewById(R.id.edit_text_index);
        edit_text_number = findViewById(R.id.edit_text_number);

        // 主线程处理消息
        handlerMessage();

        btn_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String idx = edit_text_index.getText().toString();
                String num = edit_text_number.getText().toString();
                String str_url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=" + idx + "&n=" + num;

                doRequestJSON(str_url);
            }
        });

    }

    protected void handlerMessage(){
        // 主线程中处理消息
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_REQUEST_JSON:
                        // 可以开始请求图片
                        doRequestImages();
                        break;
                    case MSG_REQUEST_IMAGE:
                        // 获得图片数据
                        Bitmap bitmap = (Bitmap) msg.obj;
                        // 更新ImageView
                        image_view.setImageBitmap(bitmap);
                        break;
                }
            }
        };
    }

    protected void doRequestJSON(String str_url){
        // 子线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 请求url并解析JSON
                InputStream stream = requestStream(str_url);
                String str_json = streamToString(stream);
                image_url_list = parseJSON(str_json);

                Message msg = Message.obtain();
                // 消息的标示
                msg.what = MSG_REQUEST_JSON;
                // 发送消息
                handler.sendMessage(msg);

            }
        });
        thread.start();
    }

    protected void doRequestImage(String str_url){
        // 子线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 请求url 获得 图片
                InputStream stream = requestStream(str_url);
                Bitmap bitmap = streamToBitmap(stream);

                Message msg = Message.obtain();
                // 消息标示
                msg.what = MSG_REQUEST_IMAGE;
                // 图片数据
                msg.obj = bitmap;
                // 发送消息
                handler.sendMessage(msg);

            }
        });
        thread.start();
    }

    protected void doRequestImages(){
        // 子线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 取出每一张图片的url
                for(int i=0; i<image_url_list.size(); ++i){
                    //拼接图片url
                    String image_url = URL_PRE + image_url_list.get(i);
                    // 请求图片
                    doRequestImage(image_url);
                    try {
                        // 让当前线程暂停3秒
                        Thread.sleep(SLEEP_MM);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    protected InputStream requestStream(String str_url){
        try {
            URL url = new URL(str_url);
            // url 连接
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            // 请求方法，如果上传可用 POST
            connection.setRequestMethod("GET");
            // 连接超时
            connection.setConnectTimeout(3000);
            // 读取超时
            connection.setReadTimeout(3000);
            // 获得输入流
            InputStream inputStream = connection.getInputStream();

            // 返回结果
            return inputStream;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected String streamToString(InputStream inputStream ){
        try {
            // 输入流转成BufferedReader
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            StringBuilder response = new StringBuilder();
            // 一次读取一行
            while((line = reader.readLine()) != null){
                // 每一行连接起来
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected Bitmap streamToBitmap(InputStream inputStream ){
        // 输入流 转 位图 Bitmap
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }

    protected  List<String> parseJSON(String response){
        try {
            // 请求结果，字符串转成JSON对象
            JSONObject jsonObject = new JSONObject(response.toString());
            // 根据key，获得 value，是一个JSON数组
            JSONArray images = jsonObject.getJSONArray("images");

            List<String> image_urls = new ArrayList<String>();
            // 遍历数组
            for (int i=0; i<images.length(); ++i){
                // 取出每一条image，也是一个JSON对象
                JSONObject image = images.getJSONObject(i);
                // 根据key，按照不同类型，获得 value
                String image_url = image.getString("url");

                Log.d(TAG, image_url);

                // 加入 list
                image_urls.add(image_url);
            }
            return image_urls;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }



}